//
//  ZallSegmentControl.m
//  SOKit
//
//  Created by soso on 13-2-21.
//  Copyright (c) 2013-2015 soso. All rights reserved.
//

#import "ZallSegmentControl.h"
#import "ZallGlobal.h"
#import "UIView+ZallAdditions.h"
#import "NSObject+ZallAdditions.h"
#import "NSString+ZallAdditions.h"

NSTimeInterval const SOSegmentAnimationDuration     = 0.25f;

@interface ZallSegmentControl () {
    UIView *_bottomLineView;
}

@property (strong, nonatomic) NSArray *items;

@property (strong, nonatomic) NSMutableArray *segments;

@property (strong, nonatomic) UIView *showCurrentOffsetView;

@end


@implementation ZallSegmentControl
@synthesize segmentDelegate;
@synthesize selectedIndex = _selectedIndex;
@synthesize contentCount = _contentCount;
@synthesize showCurrentOffsetView = _showCurrentOffsetView;
@synthesize items = _items;

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        self.bounces = NO;
        self.showsHorizontalScrollIndicator = NO;
        self.showsVerticalScrollIndicator = NO;
        
        _currentOffsetViewHeight = 3.0f;
        _showCurrentOffsetViewAlways = NO;
        _selectedIndex = 0;
        _contentCount = DEFAULT_TITLE_COUNT;
        _items = nil;
        _segments = [[NSMutableArray alloc] init];
        
        _bottomLineView = [[UIView alloc] init];
        _bottomLineView.backgroundColor = UIColorFromHexRGB(0xcccccc);
        [self addSubview:self.showCurrentOffsetView];
        [self addSubview:_bottomLineView];
        [self bringSubviewToFront:self.showCurrentOffsetView];
    }
    return (self);
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGSize size = self.bounds.size;
    NSInteger itemsCount = [_items count];
    _contentCount = (self.contentCount <= itemsCount) ? self.contentCount : itemsCount;
    CGSize buttonSize = CGSizeMake(size.width / self.contentCount, size.height);
    
    self.contentSize = CGSizeMake(buttonSize.width * itemsCount, buttonSize.height);
    
    for(NSInteger ix = 0; ix < [[self segments] count]; ix ++) {
        ZallSegmentButton *button = [[self segments] safeObjectAtIndex:ix];
        if(button && [button isKindOfClass:[ZallSegmentButton class]]) {
            button.frame = CGRectMake(buttonSize.width * ix, 0, buttonSize.width, buttonSize.height);
        }
    }
    _bottomLineView.size = CGSizeMake(self.width, 1.0f / ZallDeviceScale());
    _bottomLineView.bottom = self.height;
    [self showCurrentOffsetView].bottom = size.height;
}

#pragma mark - setter
/**
 *  @brief  设置是否显示下面默认的横线
 */
- (void)setShowDefaultBottomViewAlways:(BOOL)showDefaultBottomViewAlways {
    _showDefaultBottomViewAlways = showDefaultBottomViewAlways;
    _bottomLineView.hidden = !showDefaultBottomViewAlways;
}
- (void)setContentSize:(CGSize)contentSize {
    CGSize oldSize = self.contentSize;
    [super setContentSize:contentSize];
    if (CGSizeEqualToSize(oldSize, CGSizeZero) && !CGSizeEqualToSize(self.contentSize, CGSizeZero)) {
        [self setSelectedItemIndex:_selectedIndex animated:NO];
    }
}

- (void)setContentCount:(CGFloat)contentCount {
    [self willChangeValueForKey:@"contentCount"];
    _contentCount = contentCount;
    [self didChangeValueForKey:@"contentCount"];
    [self setNeedsLayout];
}

- (void)setItems:(NSArray *)items {
    [self willChangeValueForKey:@"items"];
    _items = [items copy];
    [self didChangeValueForKey:@"items"];
    if(self.segments) {
        [self.segments makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self.segments removeAllObjects];
    }
    for (ZallSegmentControlItem *item in items) {
        ZallSegmentButton *button = [[ZallSegmentButton alloc] initWithFrame:CGRectZero];
        button.backgroundColor = [UIColor clearColor];
        button.item = item;
        [button addTarget:self action:@selector(segmentButtonDidTouched:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        [self.segments addObject:button];
    }
    [self setNeedsLayout];
}

- (void)setSelectedItemIndex:(NSInteger)index animated:(BOOL)animated {
    [self willChangeValueForKey:@"selectedIndex"];
    _selectedIndex = index;
    [self didChangeValueForKey:@"selectedIndex"];
    CGSize size = self.bounds.size;
    CGFloat ct_x = MIN(self.contentSize.width - size.width, MAX(0, (_selectedIndex + 0.5f) * size.width / self.contentCount - size.width / 2.0f));
    [self setContentOffset:CGPointMake(ct_x, self.contentOffset.y) animated:animated];
    
    for(NSInteger ix = 0; ix < [[self segments] count]; ix ++) {
        ZallSegmentButton *button = (ZallSegmentButton *)[[self segments] safeObjectAtIndex:ix];
        [button setDidHighlighted:(index == ix)];
        if(!self.showCurrentOffsetViewAlways) {
            self.showCurrentOffsetView.hidden = YES;
        }
    }
}

- (void)setCurrentOffset:(CGPoint)offset animated:(BOOL)animated {
    self.showCurrentOffsetView.hidden = NO;
    [self bringSubviewToFront:self.showCurrentOffsetView];
    NSInteger cur = (NSInteger)floorf(offset.x + 0.5f);
    NSInteger nex = cur + 1;
    //根据类型设置滑动条的宽度
    CGFloat curWidth = (self.width - self.segments.count * 2 * 6) / self.segments.count;
    CGFloat nexWidth = (self.width - self.segments.count * 2 * 6) / self.segments.count;
    
    //    curWidth = (self.width - 64.f) / self.segments.count;
    //    nexWidth = (self.width - 64.f) / self.segments.count;
    CGFloat width = ABS(ABS(cur) - ABS(offset.x)) * nexWidth + ABS(ABS(nex) - ABS(offset.x)) * curWidth;
    [UIView animateWithDuration:(animated ? SOSegmentAnimationDuration : 0) animations:^{
        self.showCurrentOffsetView.width = width;
        self.showCurrentOffsetView.centerX = (cur + 0.5f) * CGRectGetWidth(self.bounds) / self.contentCount;
    }];
}

- (void)setShowCurrentOffsetViewColor:(UIColor *)showCurrentOffsetViewColor {
    [self willChangeValueForKey:@"showCurrentOffsetViewColor"];
    _showCurrentOffsetViewColor = showCurrentOffsetViewColor;
    [self didChangeValueForKey:@"showCurrentOffsetViewColor"];
    self.showCurrentOffsetView.backgroundColor = _showCurrentOffsetViewColor;
}
#pragma mark -

#pragma mark - getter
- (CGFloat)contentCount {
    return (MAX(1, _contentCount));
}

- (UIView *)showCurrentOffsetView {
    if(!_showCurrentOffsetView) {
        _showCurrentOffsetView = [[UIView alloc] init];
//        _showCurrentOffsetView.backgroundColor = UIColorFromHexRGB(0xdf302f);
        //当前被选中的视图,底部颜色为卓尔绿,修改人:王方
        if (isZJSDriver) {
            _showCurrentOffsetView.backgroundColor = UIColorFromHexRGB(0x2eb6aa);
        }else if (isZJSUser) {
            _showCurrentOffsetView.backgroundColor = UIColorFromHexRGB(0xdf302f);
        }
        _showCurrentOffsetView.size = CGSizeMake(self.contentSize.width / MAX(1, [[self items] count]), self.currentOffsetViewHeight);
    }
    return (_showCurrentOffsetView);
}

- (NSArray *)items {
    return ([NSArray arrayWithArray:_items]);
}

- (NSInteger)indexOfObject:(ZallSegmentButton *)object {
    return ([[self segments] indexOfObject:object]);
}

- (ZallSegmentButton *)buttonAtIndex:(NSInteger)index {
    return ([[self segments] safeObjectAtIndex:index]);
}
#pragma mark -

#pragma mark - actions
- (void)segmentButtonDidTouched:(ZallSegmentButton *)button {
    if (self.segmentDelegate && [self.segmentDelegate respondsToSelector:@selector(segmentControl:didSelectButton:atIndex:)]) {
        NSInteger index = [self indexOfObject:button];
        [self.segmentDelegate segmentControl:self didSelectButton:button atIndex:index];
    }
}
#pragma mark -

@end
